package cn.tjjcy.service.process;

import cn.tjjcy.common.DmMsg;
import cn.tjjcy.common.FileDocUtils;
import cn.tjjcy.common.GzResult;
import cn.tjjcy.dao.TAjxxMapper;
import cn.tjjcy.domain.RealGzConfEntity;
import cn.tjjcy.domain.TAjxxEntity;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class ScbgProcessService extends DefaultProcessService {

    @Value("${oct.doc.path:/doc/}")
    private String docPath;

    @Autowired
    private TAjxxMapper tAjxxMapper;

    //审查逮捕阶段在逮捕/不逮捕之前，编辑审查报告时【审查逮捕认定的案件事实及证据】必须编写(重点)
    @Override
    public GzResult gzJudge(DmMsg dmMsg, RealGzConfEntity realGzConfEntity) {
        try {
            GzResult judgeResult = super.gzJudge(dmMsg, realGzConfEntity);
            if(Objects.isNull(judgeResult)||!judgeResult.getGzResult()){
                return null;
            }

            String table = dmMsg.getTable();
            String sourceTableName = table.split("\\.")[1];
            Map<String, Object> judgeResultMap = judgeResult.getGzMap();
            String wsPath = judgeResultMap.get("ws_path").toString();
            String content = FileDocUtils.parseToString(new File(docPath + wsPath));
            if(content.contains("审查逮捕认定的案件事实及证据")){
                TAjxxEntity tAjxxEntity=new TAjxxEntity();
                tAjxxEntity.setXxqd("已编写");
                tAjxxEntity.setXxzt(1);
                tAjxxEntity.setXxys("green");
                UpdateWrapper updateWrapper=new UpdateWrapper();
                updateWrapper.eq("bmsah",judgeResult.getBmsah());
                updateWrapper.eq("gzid",realGzConfEntity.getGzId());
                Integer i = tAjxxMapper.update(tAjxxEntity,updateWrapper);
                log.info("【规则[{}]】[{}] 未触发或更新审查逮捕事实及证据规则,结果:[{}]",
                        realGzConfEntity.getId(),judgeResult.getBmsah(), realGzConfEntity.getId(),i);
                return GzResult.judgeFail("【规则["+realGzConfEntity.getId()+"]】未触发或更新审查逮捕事实及证据规则["+i+"]"
                        ,judgeResult.getGzSql(),judgeResult.getGzMap());
            }else{
                log.info("【规则[{}]】 表:[{}] SQL:[{}] 触发审查逮捕事实及证据规则",
                        realGzConfEntity.getId(), sourceTableName, judgeResult.getGzSql());
                return GzResult.judgeSuccess(judgeResult.getGzMap(),judgeResult.getGzSql());
            }
        }catch (Exception e){
            log.error("【规则[{}]】SCBGProcessService gzJudge error",realGzConfEntity.getId(),e);
            return null;
        }
    }

}
